var $state = JSON.parse(localStorage.$state ? localStorage.$state : "{}");

/* Date.prototype.Format = function(fmt) {
  // function dateFormat(fmt) {
  var o = {
    "M+": this.getMonth() + 1,
    "d+": this.getDate(),
    "H+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds(),
    "q+": Math.floor((this.getMonth() + 3) / 3),
    "S": this.getMilliseconds()
  };
  var year = this.getFullYear();
  var yearstr = year + '';
  yearstr = yearstr.length >= 4 ? yearstr : '0000'.substr(0, 4 - yearstr.length) + yearstr;

  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (yearstr + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
} */

/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
(function($, owner) {
  owner.dateFormat = function(dateObj, fmt) {
    var o = {
      "M+": dateObj.getMonth() + 1,
      "d+": dateObj.getDate(),
      "H+": dateObj.getHours(),
      "m+": dateObj.getMinutes(),
      "s+": dateObj.getSeconds(),
      "q+": Math.floor((dateObj.getMonth() + 3) / 3),
      "S": dateObj.getMilliseconds()
    };
    var year = dateObj.getFullYear();
    var yearstr = year + '';
    yearstr = yearstr.length >= 4 ? yearstr : '0000'.substr(0, 4 - yearstr.length) + yearstr;

    if (/(y+)/.test(fmt))
      fmt = fmt.replace(RegExp.$1, (yearstr + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  }

  owner.toPage = function(page) {
    $.openWindow({
      url: page,
      id: page.split('.')[1],
      show: {
        aniShow: 'pop-in'
      },
      waiting: {
        autoShow: false
      }
    });
  }

  owner.createOrderNo = function() {
    var nowObj = new Date(),
      orderNo = '';

    /* orderNo += String(nowObj.getFullYear());
    orderNo += String(nowObj.getMonth() + 1);
    orderNo += String(nowObj.getDate());
    orderNo += String(nowObj.getHours());
    orderNo += String(nowObj.getMinutes());
    orderNo += String(nowObj.getSeconds());
    orderNo += String(nowObj.getMilliseconds()); */

    // orderNo = nowObj.Format('yyyyMMddHHmmssS');
    orderNo = owner.dateFormat(nowObj, 'yyyyMMddHHmmssS');

    return orderNo;
  }

  owner.cutStr = function(str, len) {
    var str_length = 0,
      str_len = 0,
      str_cut = new String();
    str_len = str.length;
    for (var i = 0; i < str_len; i++) {
      a = str.charAt(i);
      str_length++;
      if (escape(a).length > 4) {
        //中文字符的长度经编码之后大于4  
        str_length++;
      }
      str_cut = str_cut.concat(a);
      if (str_length >= len) {
        str_cut = str_cut.concat("...");
        return str_cut;
      }
    }
    //如果给定字符串小于指定长度，则返回源字符串；  
    if (str_length < len) {
      return str;
    }
  }

  owner.getQueryString = function(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", 'i'); // 匹配目标参数
    var result = window.location.search.substr(1).match(reg); // 对querystring匹配目标参数
    if (result != null) {
      return decodeURIComponent(result[2]);
    } else {
      return null;
    }
  }

  owner.clientType = {
    versions: function() {
      var ua = navigator.userAgent,
        app = navigator.appVersion;
      return {
        trident: ua.indexOf('Trident') > -1, // IE内核
        presto: ua.indexOf('Presto') > -1, // opera内核
        webKit: ua.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
        mobile: !!ua.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
        ios: !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
        android: ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1, // android终端
        iPhone: ua.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
        iPad: ua.indexOf('iPad') > -1, // 是否iPad
        webApp: ua.indexOf('Safari') == -1, // 是否web应该程序，没有头部与底部
        weixin: ua.indexOf('MicroMessenger') > -1, // 是否微信 （2015-01-22新增）
        qq: ua.match(/\sQQ/i) == " qq" // 是否QQ
      }
    }(),
    language: (navigator.browserLanguage || navigator.language).toLowerCase()
  }

  /**
   * 用户登录
   **/
  owner.login = function(loginInfo, callback) {
    callback = callback || $.noop;
    loginInfo = loginInfo || {};
    loginInfo.username = loginInfo.username || '';
    loginInfo.password = loginInfo.password || '';
    retInfo = { code: 600 };
    if (loginInfo.username.length < 5) {
      retInfo.msg = '账号最短为 5 个字符';
      return callback(retInfo);
    }
    if (loginInfo.password) {
      if (loginInfo.password.length < 6) {
        retInfo.msg = '密码最短为 6 个字符';
        return callback(retInfo);
      }
    }

    var users = JSON.parse(localStorage.getItem('$users') || '[]');

    var authed = users.some(function(user) {
      return loginInfo.username == user.username && loginInfo.password == user.password;
    });
    var reqUrl = API.postLogin + '?login_type=' + loginInfo.login_type;
    delete loginInfo.login_type;
    if (authed) {
      http.post(reqUrl, loginInfo, res => {
        loginInfo.token = res.data.token;
        return owner.createState(loginInfo, callback, res);
      });
    } else {
      http.post(reqUrl, loginInfo, res => {
        loginInfo.token = res.data.token;
        return owner.createState(loginInfo, callback, res);
      });
    }
  };

  owner.createState = function(loginInfo, callback, res) {
    var state = owner.getState();
    state.username = loginInfo.username;
    state.token = loginInfo.token;
    owner.setState(state);
    return callback(res);
  };

  /**
   * 新用户注册
   **/
  owner.reg = function(regInfo, callback) {
    callback = callback || $.noop;
    regInfo = regInfo || {};
    regInfo.account = regInfo.account || '';
    regInfo.code = regInfo.code || '';
    regInfo.password = regInfo.password || '';
    verificationRule = /(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/;
    if (!regInfo.account) {
      return callback('手机号输入为空');
    }
    if (regInfo.account.length < 11) {
      return callback('手机号为11位,请重新输入');
    }
    if (!verificationRule.test(regInfo.account)) {
      return callback('手机号输入有误!请重新输入');
    }
    if (!regInfo.code) {
      return callback('验证码输入为空');
    }
    if (regInfo.code.length < 6) {
      return callback('验证码为6位');
    }
    if (regInfo.password.length < 6) {
      return callback('密码最短需要 6 个字符');
    }
    var users = JSON.parse(localStorage.getItem('$users') || '[]');
    users.push(regInfo);
    localStorage.setItem('$users', JSON.stringify(users));
    return callback();
  };

  /**
   * 获取当前状态
   **/
  owner.getState = function() {
    var stateText = localStorage.getItem('$state') || "{}";
    return JSON.parse(stateText);
  };

  /**
   * 设置当前状态
   **/
  owner.setState = function(state) {
    state = state || {};
    localStorage.setItem('$state', JSON.stringify(state));
    //var settings = owner.getSettings();
    //settings.gestures = '';
    //owner.setSettings(settings);
  };

  var checkEmail = function(email) {
    email = email || '';
    return (email.length > 3 && email.indexOf('@') > -1);
  };

  /**
   * 找回密码
   **/
  owner.forgetPassword = function(email, callback) {
    callback = callback || $.noop;
    if (!checkEmail(email)) {
      return callback('邮箱地址不合法');
    }
    return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
  };

  /**
   * 获取应用本地配置
   **/
  owner.setSettings = function(settings) {
    settings = settings || {};
    localStorage.setItem('$settings', JSON.stringify(settings));
  }

  /**
   * 设置应用本地配置
   **/
  owner.getSettings = function() {
      var settingsText = localStorage.getItem('$settings') || "{}";
      return JSON.parse(settingsText);
    }
    /**
     * 获取本地是否安装客户端
     **/
  owner.isInstalled = function(id) {
    if (id === 'qihoo' && mui.os.plus) {
      return true;
    }
    if (mui.os.android) {
      var main = plus.android.runtimeMainActivity();
      var packageManager = main.getPackageManager();
      var PackageManager = plus.android.importClass(packageManager)
      var packageName = {
        "qq": "com.tencent.mobileqq",
        "weixin": "com.tencent.mm",
        "sinaweibo": "com.sina.weibo"
      }
      try {
        return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
      } catch (e) {}
    } else {
      switch (id) {
        case "qq":
          var TencentOAuth = plus.ios.import("TencentOAuth");
          return TencentOAuth.iphoneQQInstalled();
        case "weixin":
          var WXApi = plus.ios.import("WXApi");
          return WXApi.isWXAppInstalled()
        case "sinaweibo":
          var SinaAPI = plus.ios.import("WeiboSDK");
          return SinaAPI.isWeiboAppInstalled()
        default:
          break;
      }
    }
  }
}(mui, window.app = {}));